package com.zb.kc.commonutils;

import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一返回结果的类
 */
public class R implements Serializable {

    /**
     * 分页查询返回的对象名称
     */
    private final static String pageStr = "page";

    /**
     * 普通结果返回的对象名称
     */
    private final static String objStr = "item";

    @ApiModelProperty("返回码")
    private Integer code;

    @ApiModelProperty("返回消息")
    private String msg;

    @ApiModelProperty("返回数据")
    private Map<String, Object> data = new HashMap<>();

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    // 把构造方法私有化
    private R() {
    }

    /**
     * 根据传进来的枚举对象返回结果
     *
     * @param rc
     * @return
     */
    private static R res(ResultCode rc) {
        R r = new R();
        r.setCode(rc.getCode());
        r.setMsg(rc.getMsg());
        return r;
    }


    /**
     * 最简单的直接返回成功
     *
     * @return
     */
    public static R ok() {
        return res(ResultCode.SUUCESS);
    }

    public static R ok(ResultCode rc) {
        return res(rc);
    }

    /**
     * 失败的静态方法
     *
     * @return
     */
    public static R err() {
        return res(ResultCode.ERROR);
    }


    public static R err(ResultCode rc) {
        return res(rc);
    }

    /**
     * 设置返回的消息
     * 返回当前对象，方便链式调用
     *
     * @param msg
     * @return
     */
    public R message(String msg) {
        setMsg(msg);
        return this;
    }


    /**
     * 返回任意类型的结果对象，json的结果对象名称是：item
     *
     * @param value
     * @return
     */
    public R data(Object value) {
        this.data.put(objStr, value);
        return this;
    }

    public R data(Map value) {
        this.setData(value);
        return this;
    }


    /**
     * 根据键值对设置data
     *
     * @param key
     * @param value
     * @return
     */
    public R data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    /**
     * 返回分页对象结果
     *
     * @param value
     * @return
     */
    public R dataPage(Object value) {
        this.data.put(pageStr, value);
        return this;
    }

    /**
     * 链式调用，返回code编码信息
     *
     * @param code
     * @return
     */
    public R code(Integer code) {
        setCode(code);
        return this;
    }

}
